//
//  BMUserInfoViewController.m
//  BicycleMap
//
//  Created by vedon on 5/16/16.
//  Copyright © 2016 Qianqian. All rights reserved.
//

#import "BMUserInfoViewController.h"
#import "BMUserManager.h"
#import "GSToast.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "UIActionSheet+BlocksKit.h"
#import "EPImagePickerHelper.h"
#import "SDImageCache.h"
#import "UIImageView+WebCache.h"
#import "UIBarButtonItem+BlocksKit.h"
#import "UIAlertView+BlocksKit.h"

@interface BMUserInfoViewController ()<UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingScrollView *contentScrollView;
@property (assign,nonatomic) BOOL hasPickNewImage;

@end

@implementation BMUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapAvatarView)];
    [self.userAvatar addGestureRecognizer:tapGesture];
    self.userAvatar.userInteractionEnabled = YES;
    self.userAvatar.layer.cornerRadius = self.userAvatar.frame.size.width/2;
    self.userAvatar.layer.masksToBounds = YES;
    tapGesture = nil;
    
    
    //用户已经登录的话，设置用户名和手机号码 ，性别等。并设置用户的头像 ，根据URL来获取头像
    if ([[BMUserManager shareManager] isLogin])
    {
        BMUserInfo *currentUserInfo = [BMUserManager shareManager].currentUserInfo;
        self.nameTextField.text = currentUserInfo.username;
        self.phoneTextField.text = currentUserInfo.mobile;
        self.sexSegmentedControl.selectedSegmentIndex = (currentUserInfo.gender == BMGender_male)?0:1;
        
        NSString *imageUrl = currentUserInfo.avatarUrl;
        if (imageUrl.length)
        {
            //先会查找本地是否有下载该URL 的图片，没有的就会去下载图片
            [self.userAvatar sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
        }
        
    }
    
    self.hasPickNewImage = NO;
    
    __weak BMUserInfoViewController *weakSelf = self;
    
    //右上角的保存按钮
    
    NSString *rightButtonTitle = @"登陆";
    if ([[BMUserManager shareManager] isLogin])
    {
        rightButtonTitle = @"退出登录";
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] bk_initWithTitle:rightButtonTitle style:UIBarButtonItemStylePlain handler:^(id sender) {
        
        if ([[BMUserManager shareManager] isLogin])
        {
            [[BMUserManager shareManager] logout];
            self.registerButton.hidden = NO;
            self.navigationItem.rightBarButtonItem.title = @"登录";
            
        }
        else
        {
            if (weakSelf.nameTextField.text.length == 0)
            {
                [GSToast showToastWithText:@"名字不能为空" inView:weakSelf.view];
                return ;
            }
            
            
            if (weakSelf.phoneTextField.text.length == 0)
            {
                [GSToast showToastWithText:@"手机号码不能为空" inView:weakSelf.view];
                return ;
            }
        
            
            [GSToast showProgressToastInView:self.view];
            if (![[BMUserManager shareManager] isUserAlreadyExist:self.phoneTextField.text])
            {
                [GSToast showToastWithText:@"用户不存在,请点击注册" inView:weakSelf.view];
                return;
            }
            
            [weakSelf syncUserInfo];
        }
    }];
    
    self.registerButton.hidden = [[BMUserManager shareManager] isLogin];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *)title
{
    return @"我的";
}

- (void)dealloc
{
    
}

#pragma mark - Action

- (void)didTapAvatarView
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    [actionSheet showInView:self.view];
    actionSheet = nil;
}

- (IBAction)registerAction:(id)sender
{
    if (self.nameTextField.text.length == 0)
    {
        [GSToast showToastWithText:@"名字不能为空" inView:self.view];
        return ;
    }
    
    
    if (self.phoneTextField.text.length == 0)
    {
        [GSToast showToastWithText:@"手机号码不能为空" inView:self.view];
        return ;
    }
    
    [GSToast showProgressToastInView:self.view];
    if ([[BMUserManager shareManager] isUserAlreadyExist:self.phoneTextField.text])
    {
        [GSToast showToastWithText:@"用户已经存在,请点击登陆" inView:self.view];
    }
    else
    {
        [self syncUserInfo];
    }
    
}

#pragma mark - Private

- (void)syncUserAvatar
{
    [[BMUserManager shareManager] uploadUserAvatar:self.userAvatar.image completedBlock:^(NSString *fileUrl, NSError *error) {
        if (!error)
        {
        
            //上传头像成功
            [GSToast showToastWithText:@"保存 " inView:self.view];
            self.hasPickNewImage = NO;
            
            
            //保存用户头像的URL 到本地
            [[[BMUserManager shareManager] currentUserInfo] setAvatarUrl:fileUrl];
            [[BMUserManager shareManager] save];
            
            //根据URL，缓存用户的头像。意思就是：根据URL来查找图片的时候，先查找本地的图片，有的话就不需要请求网络，没有的话就请求网络，下载头像
            [[SDImageCache sharedImageCache] storeImage:self.userAvatar.image forKey:fileUrl];
            
        }
        else
        {
            [GSToast showToastWithText:@"上传头像失败" inView:self.view];
        }
        
    }];
}

- (void)syncUserInfo
{
    //当手机号码和用户名同时不为空的时候，就把用户的信息保存到云端（leanCloud）
    if (self.phoneTextField.text.length && self.nameTextField.text.length)
    {
        
        BMUserInfo *userInfo = [[BMUserInfo alloc] init];
        userInfo.username = self.nameTextField.text;
        userInfo.mobile = self.phoneTextField.text;
        userInfo.gender = (self.sexSegmentedControl.selectedSegmentIndex == 0)?BMGender_male:BMGender_female;
        
        
        //首先保存用户的姓名和手机号码，保存成功后再上传用户的头像
        
        [[BMUserManager shareManager] saveWithUserInfo:userInfo completedBlock:^(AVObject *avObject, NSError *error) {
            
            if (error)
            {
                [GSToast showToastWithText:@"保存失败，请检查网络" inView:self.view];
            }
            else
            {
                //用户选择了头像
                if (self.hasPickNewImage)
                {
                    //上传头像
                    [self syncUserAvatar];
                }
                else
                {
                    [GSToast showToastWithText:@"登录成功" inView:self.view];
                    //把键盘退下去
                    [[UIApplication sharedApplication].keyWindow endEditing:YES];
                }
                self.registerButton.hidden = YES;
                self.navigationItem.rightBarButtonItem.title = @"退出登录";
            }
        }];
    }
    else
    {
        [GSToast showToastWithText:@"用户名和手机号码不能为空哦" inView:self.view];
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([buttonTitle isEqualToString:@"取消"]) {
        return;
    }
    
    //当在弹出框上选择拍照的时候，则打开相机

    
    
    ImagePickerType type = StillImage;
    if ([buttonTitle isEqualToString:@"拍照"]) {
        type = Camera;
    } else {
        type = StillImage;
    }
    
    //根据选择的类型打开相机或者打开相册选择图片。
    [[EPImagePickerHelper sharedInstance] showImagePickerWithController:self andType:type finishPickingBlock:^(UIImage *image, NSError *error ,PHAsset *asset) {
        
        //选择图片后，会执行这里的函数
        assert(error == nil);
        if (image && error == nil)
        {
            self.hasPickNewImage = YES;
            
            //更新头像
            self.userAvatar.image = image;
            
        }
        
    } cancelBlock:^{
        //不选择图片或者取消拍照，会执行这里的函数。
        
        //Do nothing
    }];
}


@end
